package com.yanq.liancar.activity;
/*
 *  @创建者     Administrator
 *  @创建时间   2018/9/26  17:06
 *  @描述       ${TODO}
 */


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;

import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.PayResult;
import com.yanq.liancar.bean.ServiceAliPayBean;
import com.yanq.liancar.bean.ServiceOrderBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.WeChatPayBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderPaymentActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_ServiceType)
    TextView tvServiceType;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_carType)
    TextView tvCarType;

    @BindView(R.id.tv_moneyVoucher)
    TextView tvMoneyVoucher;
    @BindView(R.id.tv_ActualPayment)
    TextView tvActualPayment;
    @BindView(R.id.rb_wechat)
    RadioButton rbWechat;
    @BindView(R.id.rb_ali)
    RadioButton rbAli;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.ll_zhifu)
    LinearLayout llZhifu;
    @BindView(R.id.tv_xiadan)
    TextView tvXiadan;
    @BindView(R.id.rl_daijinquan)
    RelativeLayout mRelativeLayout;

    private ServiceOrderBean.DataBean mDataBean;
    private String cashcoupon_id,service_id ,id,orderID,onum;
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**

                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。

                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    LogUtils.e("resultInfo====", resultInfo);
                    LogUtils.e("resultStatus====", resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(OrderPaymentActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        RxToast.success("下单成功");
                        Bundle bundle = new Bundle();
                        bundle.putString("orderID", orderID);
                        RxActivityTool.skipActivityAndFinish(OrderPaymentActivity.this, PurchaseSuccessActivity.class, bundle);
                    } else {

                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(OrderPaymentActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

            }

        }

    };
    private IWXAPI api;
    private static final String APP_ID = "wxd2e19fc6b6f17ec0";
    private int payType = 2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_payment);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);
        mTvTitle.setText("订单支付");
        mDataBean = (ServiceOrderBean.DataBean) getIntent().getExtras().getSerializable("data");
        tvServiceType.setText(mDataBean.getOrder().getServiceName());
        tvPrice.setText(mDataBean.getOrder().getAllPrice() + "");
        if (mDataBean.getOrder().getCarType() == 0) {
            tvCarType.setText("小型汽车");
        } else if (mDataBean.getOrder().getCarType() == 1) {
            tvCarType.setText("大型汽车");
        } else {
            tvCarType.setText("SUV汽车");
        }

        if (null != mDataBean.getOrder().getCcId()) {
            mRelativeLayout.setVisibility(View.VISIBLE);
            tvMoneyVoucher.setText(mDataBean.getOrder().getSrcPrice().subtract(mDataBean.getOrder().getAllPrice()) + "");
        } else {
            mRelativeLayout.setVisibility(View.GONE);
        }
        tvActualPayment.setText(mDataBean.getOrder().getAllPrice() + "");
        onum=mDataBean.getOrder().getOnum();
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_wechat:
                        payType = 2;
                        break;
                    case R.id.rb_ali:
                        payType = 1;
                        break;
                }
            }
        });
    }


    @OnClick(R.id.tv_pay)
    public void onViewClicked() {
        if (payType==1){
            Payment();
        }else {
            WeChatPayment();
        }
    }

    //微信支付
    private void WeChatPayment(){
        api = WXAPIFactory.createWXAPI(this,APP_ID);
        api.registerApp(APP_ID);
        OkGo.<String>post(Config.s + "llc/carServiceWXPay")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("servicePrice",tvActualPayment.getText().toString().trim())
                .params("cashcoupon_id",cashcoupon_id)
               .params("onum", onum)
//                .params("serviceName", serviceName)
                .params("carType", mDataBean.getOrder().getCarType())
                .params("service_id", service_id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        WeChatPayBean baseBean=gson.fromJson(response.body(),WeChatPayBean.class);
                        if (baseBean.isIsSuccess()){
                            PayReq request = new PayReq();
                            request.appId = baseBean.getData().getAppid();
                            request.partnerId =baseBean.getData().getPartnerId();
                            request.prepayId= baseBean.getData().getPrepayId();
                            request.packageValue = baseBean.getData().getPackageValue();
                            request.nonceStr= baseBean.getData().getNonceStr();
                            request.timeStamp= baseBean.getData().getTimeStamp();
                            request.sign= baseBean.getData().getSign();
                            api.sendReq(request);
                            LogUtils.e(" api.sendReq=====",api.sendReq(request)+"");
                        }else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }


                });


        //        String order_id=Utils.md5(UUID.randomUUID().toString().replace("_","")+System.currentTimeMillis());
        //        Log.e("dadadassda", price.replace("¥",""));
        //        WechatPayTools.wechatPayUnifyOrder(mContext,
        //            "wxd2e19fc6b6f17ec0", //微信分配的APP_ID
        //            "1513987451", //微信分配的 PARTNER_ID (商户ID)
        //            "042732fcd9da459da435cdffba5bd01d", //微信分配的 PRIVATE_KEY (私钥)
        //            new WechatModel(order_id, //订单ID (唯一)
        //                            price.replace("¥",""), //价格
        //                        tvPayName.getText().toString().trim(), //商品名称
        //                        "qqqqqqq"), //商品描述详情
        //                                new OnSuccessAndErrorListener() {
        //        @Override
        //        public void onSuccess(String s) {
        //            RxToast.success(s);
        //        }
        //
        //        @Override
        //        public void onError(String s) {
        //            RxToast.error(s);
        //        }
        //    });

    }

    //支付接口(标准洗车)
    private void Payment(){
        OkGo.<String>post(Config.s + "llc/carServiceAliPay")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("servicePrice", tvActualPayment.getText().toString().trim())
                .params("cashcoupon_id", cashcoupon_id)
                .params("onum", onum)
//                .params("serviceName", serviceName)
                .params("carType", mDataBean.getOrder().getCarType())
                .params("service_id", service_id)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        final ServiceAliPayBean baseBean=gson.fromJson(response.body(),ServiceAliPayBean.class);
                        if (baseBean.isIsSuccess()){
                            final String info= baseBean.getData().getSigned_content();
                            LogUtils.e("加签info===",info);
                            if ("".equals(info)||!TextUtils.isEmpty(info)){
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(OrderPaymentActivity.this);
                                        Map<String, String> result = alipay.payV2(info, true);

                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        mHandler.sendMessage(msg);
                                        orderID=baseBean.getData().getOnum();
                                        LogUtils.e("13123131",baseBean.getData().getOnum()+"");
                                    }
                                };
                                // 必须异步调用
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            }
                        }else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }
                });
    }
}
